<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/9/4
 * Time: 8:43
 */

namespace app\admin\service;


use FontLib\TrueType\Header;

class HttpClient
{
    private static $header=[];
    private  static  $cookie=null;
    public static function get($url,$param=[])
    {
        return self::curl($url,$param,'get');
    }
    public static function post($url,$param,$extra=[])
    {
        return self::curl($url,$param,'post');
    }
    protected  static function curl($url,$param,$method='post')
    {
        $calculate_time1=microtime(time());
        // curl 初始化
        $curl = curl_init();
        // curl 设置
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_CERTINFO, true);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl,CURLOPT_FOLLOWLOCATION,1); //函数加入这条语句
        // 判断 $data get  or post
        /*
        if ( !empty($data) ) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        */
        if(isset(Yii::$app->params['curl']) && isset(Yii::$app->params['curl']['timeout']))
        {
            curl_setopt($curl,CURLOPT_TIMEOUT,Yii::$app->params['curl']['timeout']);
        }else{
            curl_setopt($curl,CURLOPT_TIMEOUT,5);
        }
        if(array_key_exists("HTTP_USER_AGENT",$_SERVER))
        {
            curl_setopt($curl,CURLOPT_USERAGENT,$_SERVER['HTTP_USER_AGENT']);
        }
        if(!empty(self::$headers))
        {
            $headerArr=[];
            foreach (self::$header as $k=>$v) {
                    $headerArr[]=$k.":".$v;
            }
            curl_setopt($curl,CURLOPT_HEADER,$headerArr); //构造IP地址
        }
        if(empty(self::$cookie))
        {
            curl_setopt($curl,CURLOPT_COOKIE,self::cookie);
        }
        if($method=="POST")
        {
            curl_setopt($curl,CURLOPT_POST,TRUE);
            if(is_array($param))
            {
                $param=http_build_query($param);
            }
            curl_setopt($curl,CURLOPT_POSTFIELDS,$param);

        }else{
            curl_setopt($curl,CURLOPT_POST,false);
        }
        // 执行
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;

    }
    public static function setHeader($header)
    {
        self::$header=$header;
    }
    public static  function setCookie($cookie)
    {
        self::$cookie=$cookie;
    }
}